/**
 * 任务数据管理 Composable
 */
import { ref, computed } from 'vue'
import { NETWORK_CONFIG } from '@/config/network.js'
import { getAvatarDisplayUrl } from '@/utils/imageUtils.js'

export function useTaskData() {
  // 响应式数据
  const taskData = ref(null)
  const loading = ref(false)
  const error = ref('')
  const refreshing = ref(false)

  // 计算属性
  const showTaskActions = computed(() => {
    if (!taskData.value) return false
    return taskData.value.status === '0' || taskData.value.status === '1'
  })

  const canCancelApply = computed(() => {
    if (!taskData.value) return false
    return taskData.value.status === '0' && taskData.value.userApplied
  })

  const canRequestCancel = computed(() => {
    if (!taskData.value) return false
    return taskData.value.status === '1' && taskData.value.isChallenger
  })

  const canDeleteTask = computed(() => {
    if (!taskData.value) return false
    return taskData.value.status === '0' || taskData.value.status === '1'
  })

  const isPublisherAndInProgress = computed(() => {
    if (!taskData.value) return false
    return taskData.value.status === '1' && taskData.value.isPublisher
  })

  const showApplyCompleteBtn = computed(() => {
    if (!taskData.value) return false
    return taskData.value.status === '1' && taskData.value.isChallenger
  })

  // 方法
  const fetchTaskDetail = async (taskId) => {
    if (!taskId) return

    loading.value = true
    error.value = ''

    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        throw new Error('请先登录')
      }

      const response = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/task/${taskId}`,
        method: 'GET',
        header: {
          'Access-Token': `Bearer ${token}`
        }
      })

      if (response.data && response.data.success) {
        taskData.value = response.data.data
      } else {
        throw new Error(response.data?.message || '获取任务详情失败')
      }
    } catch (err) {
      error.value = err.message || '获取任务详情失败'
      console.error('获取任务详情失败:', err)
    } finally {
      loading.value = false
    }
  }

  const refreshTaskData = async () => {
    if (!taskData.value?.taskId) return

    refreshing.value = true
    try {
      await fetchTaskDetail(taskData.value.taskId)
    } finally {
      refreshing.value = false
    }
  }

  const formatNumber = (num) => {
    if (!num) return '0'
    return Number(num).toLocaleString()
  }

  const getStatusText = (status) => {
    const statusMap = {
      '0': '待接取',
      '1': '进行中',
      '2': '已完成',
      '3': '已取消',
      '4': '已过期'
    }
    return statusMap[status] || '未知状态'
  }

  const getAvatarUrl = (avatarUrl) => {
    return getAvatarDisplayUrl(avatarUrl)
  }

  return {
    // 响应式数据
    taskData,
    loading,
    error,
    refreshing,
    
    // 计算属性
    showTaskActions,
    canCancelApply,
    canRequestCancel,
    canDeleteTask,
    isPublisherAndInProgress,
    showApplyCompleteBtn,
    
    // 方法
    fetchTaskDetail,
    refreshTaskData,
    formatNumber,
    getStatusText,
    getAvatarUrl
  }
}
